import av
import os
import glob
import warnings
import shutil
from tqdm import tqdm
import argparse
from moviepy.editor import VideoFileClip
from pptx import Presentation
from pptx.util import Inches
import re
list_video = []
prs = Presentation()
def area(old_video,new_video):
    print('截取指定区域视频')
    clip = VideoFileClip(old_video,audio=False)
    ((clip.crop(x1=0, y1=100, x2=1630, y2=100 + 890).write_videofile(new_video)))  # (左上角x1，y1;右下角x2,y2)
# 提取关键帧
def extract_video(filename):
    index=0
    container = av.open(filename)
    #Signal that we only want to look at keyframes.
    stream = container.streams.video[0]
    stream.codec_context.skip_frame = 'NONKEY'
    print('开始给刘导截'+filename+'的PPT')
    for frame in tqdm(container.decode(stream)):
        frame.to_image().save('{:d}.png'.format(index),quality=80)
        index+=1
#写入ppt
def write_ppt(dir_video_des,ppt_path):
    path=re.findall("./.*/",ppt_path)[0]
    if not os.path.exists(path):
        os.makedirs(path)

    path_file_number = glob.glob(pathname=dir_video_des+'*.png')
    for item_filename in tqdm(range(0,len(path_file_number))):  # 循环遍历所有图片
        img_path = dir_video_des + str(item_filename)+'.png'  # 图片名称一定要对
        blank_slide_layout = prs.slide_layouts[6]
        slide = prs.slides.add_slide(blank_slide_layout)

        left = top = Inches(0)  # 设置插入的位置
        width, height = Inches(10), Inches(7.5)
        pic = slide.shapes.add_picture(img_path, left, top, width, height)  # 将图片添加到PPT
    prs.save(ppt_path)

def exit_video(dir_video_src):
    for item_filename in os.listdir(dir_video_src):
        list_video.append(item_filename)
        print('读取的视频：',item_filename)
    if len(list_video) == 0:
        print("视频文件不存在")


def parse_args():
    """
    Parse input arguments
    """
    parser = argparse.ArgumentParser(description='Process pic')
    parser.add_argument('-old', help='video to process', dest='old', default=None, type=str)
    parser.add_argument('-new', help='pic to store', dest='new', default=None, type=str)
    parser.add_argument('-i', help='video to process', dest='input', default=None, type=str)
    parser.add_argument('-o', help='pic to store', dest='output', default=None, type=str)
    parser.add_argument('-pic', help='pic to store', dest='pic_path', default=None, type=str)
    parser.add_argument('-ppt', help='pic to store', dest='ppt_path', default=None, type=str)
    #input为输入视频的路径 ，output为输出存放图片的路径
    args = parser.parse_args()
    return args


def main(dir_video_src,dir_video_des):
    exit_video(dir_video_src)
    for filename in list_video:
        file_dir_desc = os.path.join(dir_video_des, filename)
        if not os.path.exists(file_dir_desc):
            os.makedirs(file_dir_desc)
            print("已自动创建关键帧目录：", file_dir_desc)
        else:
            print("关键帧目录已存在")
        # 提取关键帧
        extract_video(os.path.join(dir_video_src, filename))
        # 把关键帧图片放到图片目录下
        for filename_png in os.listdir(os.getcwd()):
            if ".png" in filename_png:
                # shutil.move(filename_png, file_dir_desc)
                shutil.copy2(filename_png, file_dir_desc)
                os.remove(filename_png)



if __name__=='__main__':
    args = parse_args()
    if(args.old!='' and args.new!=''):
        area(args.old,args.new)#可选
    main(args.input,args.output)
    print('PPT终于截完了！！！')
    print('将截图写入'+args.ppt_path+'中...')
    write_ppt(args.pic_path,args.ppt_path)
    print('干完活了')


